import { CloudUpload as CloudUploadIcon } from "@mui/icons-material";
import ArrowBackIosIcon from "@mui/icons-material/ArrowBackIos";
import ArrowForwardIosIcon from "@mui/icons-material/ArrowForwardIos";
import DeleteIcon from "@mui/icons-material/Delete";
import {
  Box,
  Button,
  Card,
  CardMedia,
  Divider,
  FormControlLabel,
  Grid,
  IconButton,
  Switch,
  TextField,
  Typography,
} from "@mui/material";
import CircularProgress from "@mui/material/CircularProgress";
import React, { useEffect, useRef, useState } from "react";
import { toast } from "react-toastify";
import { filterImage } from "../App";
import { uploadImageToS3 } from "../services/s3";
import FriendStyleModal from "./FriendStyleModal";

export default function PostForm({
  initialData,
  onSubmit,
  isLoading,
  friendStyles = [],
}) {
  const [formData, setFormData] = useState({
    content: "",
    imageUrls: [],
    friendStyleSn: "",
    isPremium: false,
    customProfileName: "",
    ...initialData,
  });
  const initialFormDataRef = useRef(
    initialData || {
      content: "",
      imageUrls: [],
      friendStyleSn: "",
      isPremium: false,
    }
  );
  const [uploadingImages, setUploadingImages] = useState(false);
  const [isFriendStyleModalOpen, setIsFriendStyleModalOpen] = useState(false);

  useEffect(() => {
    if (initialData) {
      initialFormDataRef.current = initialData;
      setFormData(initialData);
    }
  }, [initialData]);

  const handleChange = (e) => {
    const { name, value, checked } = e.target;
    setFormData((prev) => ({
      ...prev,
      [name]: name === "isPremium" ? checked : value,
    }));
  };

  const handleImageUpload = async (event) => {
    const files = Array.from(event.target.files);

    // Validate file types and sizes
    const validFiles = files.filter((file) => {
      if (!file.type.startsWith("image/")) {
        toast.error(`${file.name} is not an image file`);
        return false;
      }
      // 5MB size limit
      if (file.size > 5 * 1024 * 1024) {
        toast.error(`${file.name} is too large (max 5MB)`);
        return false;
      }
      return true;
    });

    if (validFiles.length === 0) return;

    if (formData.imageUrls.length + validFiles.length > 5) {
      toast.error("Maximum 5 images allowed");
      return;
    }

    setUploadingImages(true);
    try {
      const uploadPromises = validFiles.map(async (file) => {
        try {
          return await uploadImageToS3(file);
        } catch (error) {
          console.error(`Error uploading ${file.name}:`, error);
          toast.error(`Failed to upload ${file.name}: ${error.message}`);
          return null;
        }
      });

      const uploadedUrls = (await Promise.all(uploadPromises)).filter(
        (url) => url !== null
      );

      if (uploadedUrls.length > 0) {
        setFormData((prev) => ({
          ...prev,
          imageUrls: [...prev.imageUrls, ...uploadedUrls],
        }));

        if (uploadedUrls.length < validFiles.length) {
          toast.warning(
            "Some images failed to upload. Please try again with the failed images."
          );
        } else {
          toast.success("Images uploaded successfully!");
        }
      }
    } catch (error) {
      console.error("Upload error:", error);
      toast.error(`Upload failed: ${error.message}`);
    } finally {
      setUploadingImages(false);
      // Clear the input value to allow uploading the same file again
      event.target.value = "";
    }
  };

  const removeImage = (index) => {
    setFormData((prev) => ({
      ...prev,
      imageUrls: prev.imageUrls.filter((_, i) => i !== index),
    }));
  };

  const moveImageLeft = (index) => {
    if (index === 0) return;
    const newImageUrls = [...formData.imageUrls];
    [newImageUrls[index - 1], newImageUrls[index]] = [
      newImageUrls[index],
      newImageUrls[index - 1],
    ];
    setFormData((prev) => ({ ...prev, imageUrls: newImageUrls }));
  };

  const moveImageRight = (index) => {
    if (index === formData.imageUrls.length - 1) return;
    const newImageUrls = [...formData.imageUrls];
    [newImageUrls[index], newImageUrls[index + 1]] = [
      newImageUrls[index + 1],
      newImageUrls[index],
    ];
    setFormData((prev) => ({ ...prev, imageUrls: newImageUrls }));
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    if (formData.imageUrls.length === 0) {
      toast.error("At least one image is required");
      return;
    }
    onSubmit(formData);
  };

  const hasChanges = () => {
    if (!initialFormDataRef.current) return true;
    if (formData.content !== initialFormDataRef.current.content) return true;
    if (formData.isPremium !== initialFormDataRef.current.isPremium)
      return true;
    if (
      formData.imageUrls.length !== initialFormDataRef.current.imageUrls.length
    )
      return true;
    for (let i = 0; i < formData.imageUrls.length; i++) {
      if (formData.imageUrls[i] !== initialFormDataRef.current.imageUrls[i])
        return true;
    }
    return false;
  };

  const handleFriendStyleSelect = (selectedStyle) => {
    setFormData((prev) => ({
      ...prev,
      friendStyleSn: selectedStyle.sn,
      customProfileName: selectedStyle.name,
      customProfileUrl: selectedStyle.head,
    }));
    setIsFriendStyleModalOpen(false);
  };

  const handleProfileImageChange = async (e) => {
    const file = e.target.files[0];
    if (!file) return;

    // Validate file type and size
    if (!file.type.startsWith("image/")) {
      toast.error(`${file.name} is not an image file`);
      return;
    }
    if (file.size > 5 * 1024 * 1024) {
      toast.error(`${file.name} is too large (max 5MB)`);
      return;
    }

    setUploadingImages(true);
    try {
      const uploadedUrl = await uploadImageToS3(file);
      setFormData((prev) => ({
        ...prev,
        customProfileUrl: uploadedUrl,
      }));
      toast.success("Profile image uploaded successfully!");
    } catch (error) {
      console.error(`Error uploading ${file.name}:`, error);
      toast.error(`Failed to upload profile image: ${error.message}`);
    } finally {
      setUploadingImages(false);
      e.target.value = ""; // Clear the input
    }
  };

  return (
    <Box component="form" onSubmit={handleSubmit} sx={{ mt: 2 }}>
      <Grid container spacing={2} alignItems="center">
        {friendStyles.length > 0 && (
          <Grid item xs={12}>
            <Button
              variant="outlined"
              onClick={() => setIsFriendStyleModalOpen(true)}
              disabled={isLoading}
            >
              {formData.friendStyleSn
                ? `Selected: ${
                    friendStyles.find(
                      (style) => style.sn === formData.friendStyleSn
                    )?.name
                  }`
                : "Select Friend Style"}
            </Button>
          </Grid>
        )}
        {friendStyles.length === 0 && (
          <Grid item xs={12} md="auto">
            <Box
              sx={{
                display: "flex",
                flexDirection: "row",
                gap: 3,
                alignItems: "center",
                p: 2,
                border: 1,
                borderColor: "divider",
                borderRadius: 1,
                opacity: isLoading ? 0.7 : 1,
                pointerEvents: isLoading ? "none" : "auto",
              }}
            >
              {formData.customProfileUrl && (
                <Box
                  component="img"
                  src={filterImage(formData.customProfileUrl, 100)}
                  alt="Profile Preview"
                  sx={{
                    width: 100,
                    height: 100,
                    objectFit: "cover",
                    borderRadius: "50%",
                  }}
                />
              )}
              <Box sx={{ display: "flex", flexDirection: "column", gap: 2 }}>
                <TextField
                  label="Custom Profile Name"
                  name="customProfileName"
                  value={formData.customProfileName}
                  onChange={handleChange}
                  fullWidth
                  disabled={isLoading}
                />
                <Button
                  variant="outlined"
                  component="label"
                  disabled={isLoading || uploadingImages}
                >
                  {formData.customProfileUrl
                    ? "Change Profile Image"
                    : "Upload Profile Image"}
                  <input
                    type="file"
                    hidden
                    accept="image/*"
                    onChange={handleProfileImageChange}
                    disabled={isLoading || uploadingImages}
                  />
                </Button>
              </Box>
            </Box>
          </Grid>
        )}
        {formData.friendStyleSn && (
          <Grid item xs={12} md="auto">
            <Box
              sx={{
                display: "flex",
                flexDirection: "row",
                gap: 3,
                alignItems: "center",
                p: 2,
                border: 1,
                borderColor: "divider",
                borderRadius: 1,
              }}
            >
              <Box
                component="img"
                src={filterImage(
                  friendStyles.find(
                    (style) => style.sn === formData.friendStyleSn
                  )?.head,
                  100
                )}
                alt="Profile Preview"
                sx={{
                  width: 100,
                  height: 100,
                  objectFit: "cover",
                  borderRadius: "50%",
                }}
              />
              <Typography variant="h6">
                {
                  friendStyles.find(
                    (style) => style.sn === formData.friendStyleSn
                  )?.name
                }
              </Typography>
            </Box>
          </Grid>
        )}
      </Grid>
      <Divider sx={{ my: 2 }} />
      <Grid container spacing={3}>
        <Grid item xs={12}>
          <TextField
            fullWidth
            label="Content"
            name="content"
            multiline
            rows={4}
            value={formData.content}
            onChange={handleChange}
            required
            disabled={isLoading}
          />
        </Grid>

        <Grid item xs={12}>
          <Typography variant="h6" gutterBottom>
            Images (1-5 required)
          </Typography>
          <input
            accept="image/*"
            style={{ display: "none" }}
            id="image-upload"
            type="file"
            multiple
            onChange={handleImageUpload}
            disabled={
              isLoading || uploadingImages || formData.imageUrls.length >= 5
            }
          />
          <label htmlFor="image-upload">
            <Button
              variant="outlined"
              component="span"
              startIcon={
                uploadingImages ? (
                  <CircularProgress size={20} />
                ) : (
                  <CloudUploadIcon />
                )
              }
              disabled={
                isLoading || uploadingImages || formData.imageUrls.length >= 5
              }
            >
              {uploadingImages ? "Uploading..." : "Upload Images"}
            </Button>
          </label>

          <Grid container spacing={2} sx={{ mt: 2 }}>
            {formData.imageUrls.map((url, index) => (
              <Grid item xs={12} sm={6} md={4} key={index}>
                <Card>
                  <CardMedia
                    component="img"
                    height="200"
                    image={filterImage(url, 800)}
                    alt={`Image ${index + 1}`}
                  />
                  <Box
                    sx={{
                      p: 1,
                      display: "flex",
                      justifyContent: "space-between",
                      alignItems: "center",
                    }}
                  >
                    <Box>
                      {index > 0 && (
                        <IconButton
                          onClick={() => moveImageLeft(index)}
                          color="primary"
                          size="small"
                          disabled={isLoading}
                        >
                          <ArrowBackIosIcon fontSize="small" />
                        </IconButton>
                      )}
                      {index < formData.imageUrls.length - 1 && (
                        <IconButton
                          onClick={() => moveImageRight(index)}
                          color="primary"
                          size="small"
                          disabled={isLoading}
                        >
                          <ArrowForwardIosIcon fontSize="small" />
                        </IconButton>
                      )}
                    </Box>
                    <IconButton
                      onClick={() => removeImage(index)}
                      color="error"
                      size="small"
                      disabled={isLoading}
                    >
                      <DeleteIcon />
                    </IconButton>
                  </Box>
                </Card>
              </Grid>
            ))}
          </Grid>
        </Grid>

        <Grid item xs={12}>
          <FormControlLabel
            control={
              <Switch
                checked={formData.isPremium}
                onChange={handleChange}
                name="isPremium"
                disabled={isLoading}
              />
            }
            label="Premium Post"
          />
        </Grid>

        <Grid item xs={12}>
          <Box sx={{ display: "flex", justifyContent: "flex-end" }}>
            <Button
              type="submit"
              variant="contained"
              size="large"
              disabled={isLoading || uploadingImages || !hasChanges()}
            >
              {isLoading ? "Saving..." : "Save Post"}
            </Button>
          </Box>
        </Grid>
      </Grid>

      <FriendStyleModal
        open={isFriendStyleModalOpen}
        onClose={() => setIsFriendStyleModalOpen(false)}
        friendStyles={friendStyles}
        onSelectStyle={handleFriendStyleSelect}
      />
    </Box>
  );
}
